<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
        <el-form-item label="平台名称 / 代码" prop="tag">
          <el-input
            v-model="queryParams.tag"
            placeholder="请输入平台名称 / 代码"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleEdit()">创建平台</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="平台名称" prop="name" min-width="160">
          <template #default="scope">
            {{ scope.row.name || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="平台代码" prop="code" min-width="160">
          <template #default="scope">
            {{ scope.row.code || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="switcher" min-width="160">
          <template #default="scope">
            <el-tag v-if="scope.row.switcher === 'closed'" type="danger">禁用</el-tag>
            <el-tag v-else type="success">启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt" min-width="160">
          <template #default="scope">
            {{ scope.row.createdAt ? formatDate(scope.row.createdAt) : "--" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
            <el-button
              v-if="scope.row.switcher === 'closed'"
              type="text"
              @click="handleStatusSwitch([scope.row.id], 'open')"
            >
              启用
            </el-button>
            <el-button
              v-if="scope.row.switcher === 'opened'"
              type="text"
              @click="handleStatusSwitch([scope.row.id], 'close')"
            >
              禁用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="paging.page"
          v-model:page-size="paging.size"
          :page-sizes="['10', '20', '30', '50', '100']"
          :size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router";
import useToggle from "@/hooks/useToggle";
import { formatDate } from "@/utils";
import { getListApi, delIds, statusSwitch } from "@/api/platformConfig/index.api";
// import useCountries from "@/hooks/useCountries";
// const code = ref("// 请输入代码");
const router = useRouter();

// const { countriesList, getCountryName } = useCountries();
const [loading, _, setLoading] = useToggle();

const queryParams = ref({
  tag: "",
});

const paging = ref({
  page: 1,
  size: 10,
  total: 0,
});

const handleStatusSwitch = (ids, status) => {
  const tips = status == "open" ? "确定要启用吗？" : "确定要禁用吗？";
  ElMessageBox.confirm(tips, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    statusSwitch({
      ids,
      switcher: status,
    }).then(() => {
      ElMessage.success("操作成功");
      handleQuery();
    });
  });
};

const tableData = ref([]);

const handleSizeChange = (e) => {
  paging.value.size = e;
  getList();
};
const handleCurrentChange = (e) => {
  paging.value.page = e;
  getList();
};

const ids = ref([]);
const handleSelectionChange = (e) => {
  ids.value = e.map((item) => item.id);
};

const getList = async () => {
  try {
    setLoading(true);
    const res = await getListApi({
      page: paging.value.page,
      size: paging.value.size,
      tag: queryParams.value.tag,
    });
    paging.value.total = res.count;
    tableData.value = res.rows;
    setLoading(false);
  } finally {
    setLoading(false);
  }
};

const handleQuery = () => {
  paging.value.page = "1";
  getList();
};

handleQuery();

const queryFormRef = ref(null);
const handleResetQuery = () => {
  if (!queryFormRef.value) return;
  queryFormRef.value.resetFields();
  handleQuery();
};

// const handleClickBatch = (command, type, row) => {
//   const commands = {
//     edit: () => "",
//     delete: () => handleDelete(row),
//   }[`${command}`];

//   return commands && commands();
// };

const handleEdit = (row) => {
  if (!row) return router.push("/platformConfig/design");
  router.push("/platformConfig/design?code=" + row.code);
};

const handleDelete = (row) => {
  if (!row.id && ids.value.length === 0) return ElMessage.warning("请选择要删除的记录");
  const tips = `确定删除${!row.id ? `${ids.value.length}条记录` : "这条记录"}?`;

  ElMessageBox.confirm(tips, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    del();
  });

  const del = async () => {
    if (row.id) {
      const res = await delIds({ ids: [Number(row.id)] });
      console.log(res);
      if (res) {
        ElMessage.success("删除成功");
        handleQuery();
      }
      return;
    }

    const res = await delIds({ ids: ids.value });
    if (res) {
      ElMessage.success("删除成功");
      handleQuery();
    }
  };
};
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>
